package com.hfut.wxy.dao;

import com.hfut.wxy.common.parent.ParentDao;
import com.hfut.wxy.entity.mysql.WxyOrder;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import javax.transaction.Transactional;
import java.util.List;

public interface WxyOrderDao  extends ParentDao<WxyOrder,Integer> {

    @Modifying
    @Transactional
    //采用乐观锁对该行加锁
    @Query(value="update wxyOrder set executorId=?1,state=1,version=version+1 where id=?2 and version=1",nativeQuery = true)
    int changeReceiverAndSate(Integer executorId,Integer orderId);

    @Modifying
    @Transactional
    //采用乐观锁对该行加锁
    @Query(value="update wxyOrder set state=4,version=version+1 where id=?1 and version=2",nativeQuery = true)
    int cancelOrder(Integer orderId);

    @Query(value="select creatorId from  wxyOrder where id = ?1",nativeQuery = true)
    Integer findCreatorId(Integer orderId);

    @Query(value="select executorId from wxyOrder where id=?1",nativeQuery = true)
    Integer findExecutorId(Integer orderId);

    Page<WxyOrder> findAllByPickUpAddress_IdAndState(Integer pickUpId,Integer state, Pageable p);


    Page<WxyOrder> findAllByCreator_IdAndStateIn(Integer userId,List<Integer> states, Pageable pageable);

    Page<WxyOrder> findAllByCreator_Id(Integer userId, Pageable pageable);


    Page<WxyOrder> findAllByExecutor_IdAndStateIn(Integer userId, List<Integer> states, Pageable pageable);


    @Query(nativeQuery = true,value = "SELECT a.* FROM wxyorder a LEFT JOIN wxyexception b on a.id = b.orderId WHERE b.userId=?1 "+
            "UNION " +
            "SELECT * FROM wxyorder WHERE executorId=?1 order by id")
    Page<WxyOrder> findAllByExecutor_Id(Integer userId, Pageable pageable);

    @Query(nativeQuery=true,value="SELECT COUNT(0) FROM wxyorder a LEFT JOIN wxyexception b on a.id = b.orderId WHERE a.executorId =?1 or b.userId=?1")
    long countAllByExecutorId(Integer userId);

    long countAllByCreatorId(Integer userId);

//    @Query(value = "select ")
    Page<WxyOrder> findAllByState(Integer state,Pageable page);
}
